package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"lin6xcom/src/utils"
	"net/http"
	"strings"
)

type FileController struct {
}

// 上传文件--------
func (FileController) Upload(ctx *gin.Context) {

	file, err := ctx.FormFile("file")
	if err != nil {
		fmt.Println(err)
		ctx.JSON(400, gin.H{
			"code": 400,
			"msg":  "上传失败",
		})
		return
	}
	newFileName := utils.RandomName(10)
	file.Filename = newFileName + file.Filename[strings.LastIndex(file.Filename, "."):]
	if err := ctx.SaveUploadedFile(file, "./src/static/"+file.Filename); err != nil {
		ctx.String(http.StatusInternalServerError, "保存文件时出错："+err.Error())
		return
	}
	ctx.JSON(200, gin.H{
		"errno": 0,
		"data": gin.H{
			"url":  "http://lin6x.com:8088/file/" + file.Filename,
			"alt":  file.Filename,
			"href": "/file/" + file.Filename,
		},
	})
}

// 删除文件--------
func (FileController) Delete(ctx *gin.Context) {
	err := utils.DeleteFile("./src/static/" + ctx.Query("fileName"))
	if err != nil {
		ctx.JSON(400, gin.H{
			"message": "删除文件失败",
			"success": false,
		})
		fmt.Println(err)
		fmt.Println(ctx.Param("fileName"))
		return
	}
	ctx.JSON(200, gin.H{
		"code":    200,
		"message": "删除文件成功",
		"success": true,
	})
}
